<p>
  The algorithm implementation consists of mainly three parts: Defining the custom imported data, initialization of the strategy parameters, and monthly re-balancing of the portfolio.
</p>

<h3>Step 1: Defining Custom Imported Data</h3>
<p>
  We import T-Bill data from Quandl - a marketplace for financial, economic and alternative data. This requires defining a small class that tells QuantConnect how to interpret?the Quandl data.
</p>

<div class="section-example-container">

<pre class="python">class TBill(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/USTREASURY/BILLRATES.csv?api_key=XXXXXXXXX&amp;order=asc", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLiveMode):
        tbill = TBill()
        tbill.Symbol = config.Symbol
        # Example Line Format:
        # Date      4 Wk Bank Discount Rate
        # 2017-06-01 		0.8
        if not (line.strip() and line[0].isdigit()): return None
        try:
            data = line.split(',')
            value = float(data[1])*0.01
            value = decimal.Decimal(value)
            if value == 0: return None
            tbill.Time = datetime.strptime(data[0], "%Y-%m-%d")
            tbill.Value = value
            tbill["Close"] = float(value)
            return tbill;
        except ValueError:
            return None
</pre>
</div>
<p>
  We first provide the source of the data as a URL to Quandl's API in the GetSource method. We need to make sure the data is?organized in ascending order which is done with the?"order=asc" parameter.?You need to substitute the API key in the URL for your personal Quandl API token.
  The Reader method parses a line of the data file. When using custom data you need to minimally set?the Time property?and Value property. In this example we find the value property from the headings in the spreadsheet is the second column and we reference it with data[1]. We set the Close property to the same value.
</p>

<p>
  In our "Initialize" function we use the following commands to add the custom data into our portfolio.
</p>

<div class="section-example-container">

<pre class="python">self.AddData(TBill, "tbill")
self.tbill = self.Securities["tbill"].Symbol
</pre>
</div>
<h3>Step 2: Initialization of the Strategy Parameters</h3>
<p>
  In our?"Initialize" function we set the cash amount, start-end date as well as other parameters that are specific to this strategy.?We set two parameters for the regression analysis period:
</p>

<div class="section-example-container">

<pre class="python">self.regPeriod = 24
self.daysInMonth = 21
</pre>
</div>
<p>
  The variable "regPeriod" indicates how many months we are going to take into consideration in our regression analysis. We assume 21 days per month and request a historical period of approximately 2 years. We jump back in steps of 21 days and assume it is roughly 1 month of return.
  We need to set up "Schedule" function in "Initialize" so as to trigger the monthly re-balancing function every month.
</p>

<div class="section-example-container">

<pre class="python">self.Schedule.On(self.DateRules.MonthStart(self.spy), self.TimeRules.AfterMarketOpen(self.spy),Action(self.MonthlyReg))
</pre>
</div>
<h3>Step 3: Monthly Re-balancing of the Portfolio</h3>
<p>
  Every month we reconstruct the regression analysis to determine whether to be 100% long stocks or T-Bill contracts. We perform this re-balancing in the MonthlyReg function at the start of each month.?We use the History function to retrieve historical data for oil and stocks?and then divide the T-Bill rate by 12 to make it comparable to the monthly expected return of stocks.
</p>

<div class="section-example-container">

<pre class="python">hist = self.History([self.oil, self.spy], self.regPeriod*self.daysInMonth, Resolution.Daily)
oilSeries = hist.loc[str(self.oil)]['close'][self.daysInMonth-1:self.regPeriod*self.daysInMonth:self.daysInMonth]
spySeries = hist.loc[str(self.spy)]['close'][self.daysInMonth-1:self.regPeriod*self.daysInMonth:self.daysInMonth]
rf = float(self.Securities[self.tbill].Price)/12.0
</pre>
</div>
<p>
  Then we make an OLS regression by using "numpy" to make the prediction on next month's stock return.
</p>

<div class="section-example-container">

<pre class="python">x = np.array(oilSeries)
x = (np.diff(x)/x[:-1])
y = np.array(spySeries)
y = (np.diff(y)/y[:-1])
A = np.vstack([x[:-1],np.ones(len(x[:-1]))]).T
beta, alpha = np.linalg.lstsq(A,y[1:])[0]
yPred = alpha + x[-1]*beta
</pre>
</div>
<p>
  Finally, we compare the expected return of stocks with risk-free rate. If the former is larger than the latter, we invest fully in stocks; otherwise we liquidate our holdings. Because we cannot purchase T-Bill contracts the performance is likely slightly underestimated.
</p>

<div class="section-example-container">

<pre class="python">if yPred &gt; rf:
	self.SetHoldings(self.spy, 1)
else:
	self.Liquidate(self.spy)</pre>
</div>
